<template>
  <div class="sql-extractor">
    <button @click="returnFn" class="btn btn-primary retrunBUtton">
      <i class="icon">⚡</i> 返回
    </button>
    <div class="container">
      <header class="tool-header">
        <h1>SQL语句提取工具</h1>
        <p class="subtitle">提取和分析SQL文件中的特定操作语句</p>
      </header>

      <div class="tool-content">
        <!-- 文件上传区域 -->
        <div class="upload-section">
          <div class="upload-area" @click="triggerFileInput" @drop="handleDrop" @dragover.prevent>
            <input
              type="file"
              ref="fileInput"
              @change="handleFileSelect"
              accept=".sql,.txt"
              style="display: none"
            />
            <div class="upload-icon">📁</div>
            <p>点击选择SQL文件或拖拽文件到这里</p>
            <small>支持 .sql 和 .txt 文件</small>
          </div>
          <div v-if="selectedFile" class="file-info">
            <span>已选择文件: {{ selectedFile.name }}</span>
            <button @click="clearFile" class="clear-btn">清除</button>
          </div>
        </div>

        <!-- 过滤条件区域 -->
        <div class="filter-section">
          <div class="filter-group">
            <label>操作类型:</label>
            <div class="operation-buttons">
              <button
                v-for="op in operationTypes"
                :key="op.value"
                :class="{ active: selectedOperations.includes(op.value) }"
                @click="toggleOperation(op.value)"
              >
                {{ op.label }}
              </button>
            </div>
          </div>

          <div class="filter-group">
            <label>表名过滤:</label>
            <input
              type="text"
              v-model="tableFilter"
              placeholder="输入表名（可选，支持正则表达式）"
              class="table-input"
            />
          </div>

          <div class="action-buttons">
            <button @click="extractSQL" :disabled="!sqlContent" class="extract-btn">
              🔍 提取语句
            </button>
            <button @click="clearAll" class="clear-all-btn">🗑️ 清空所有</button>
          </div>
        </div>

        <!-- 结果显示区域 -->
        <div class="result-section">
          <div class="result-header">
            <h3>提取结果 ({{ extractedStatements.length }} 条)</h3>
            <button
              @click="copyResults"
              :disabled="extractedStatements.length === 0"
              class="copy-btn"
            >
              {{ copyButtonText }}
            </button>
          </div>

          <div class="result-content">
            <div v-if="extractedStatements.length === 0" class="empty-state">
              <div class="empty-icon">📊</div>
              <p>提取结果将显示在这里</p>
            </div>

            <div v-else class="statements-list">
              <div
                v-for="(statement, index) in extractedStatements"
                :key="index"
                class="statement-item"
                :class="getOperationClass(statement.operation)"
              >
                <div class="statement-header">
                  <span class="operation-tag">{{ statement.operation.toUpperCase() }}</span>
                  <span class="table-name">{{ statement.table }}</span>
                  <span class="statement-index">#{{ index + 1 }}</span>
                </div>
                <pre class="statement-sql">{{ statement.sql }}</pre>
                <div class="statement-meta">
                  <span>位置: 第{{ statement.lineNumber }}行</span>
                  <span>长度: {{ statement.sql.length }} 字符</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 统计信息 -->
        <div v-if="extractedStatements.length > 0" class="stats-section">
          <h3>统计信息</h3>
          <div class="stats-grid">
            <div class="stat-item">
              <span class="stat-label">总语句数</span>
              <span class="stat-value">{{ extractedStatements.length }}</span>
            </div>
            <div v-for="(count, op) in operationStats" :key="op" class="stat-item">
              <span class="stat-label">{{ op.toUpperCase() }}</span>
              <span class="stat-value">{{ count }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
const Router = useRouter()
// 响应式数据
const fileInput = ref(null)
const selectedFile = ref(null)
const sqlContent = ref('')
const selectedOperations = ref(['insert', 'update', 'delete', 'create', 'alter', 'drop'])
const tableFilter = ref('')
const extractedStatements = ref([])
const copyButtonText = ref('复制结果')

// 操作类型配置
const operationTypes = [
  { value: 'insert', label: 'INSERT' },
  { value: 'update', label: 'UPDATE' },
  { value: 'delete', label: 'DELETE' },
  { value: 'create', label: 'CREATE' },
  { value: 'alter', label: 'ALTER' },
  { value: 'drop', label: 'DROP' },
  { value: 'truncate', label: 'TRUNCATE' },
  { value: 'replace', label: 'REPLACE' }
]

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}
const returnFn = () => {
  Router.go(-1)
}
// 处理文件选择
const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (file) {
    readFileContent(file)
  }
}

// 处理拖拽文件
const handleDrop = (event) => {
  event.preventDefault()
  const file = event.dataTransfer.files[0]
  if (file && (file.name.endsWith('.sql') || file.name.endsWith('.txt'))) {
    readFileContent(file)
  }
}

// 读取文件内容
const readFileContent = (file) => {
  selectedFile.value = file
  const reader = new FileReader()
  reader.onload = (e) => {
    sqlContent.value = e.target.result
  }
  reader.readAsText(file)
}

// 清除文件
const clearFile = () => {
  selectedFile.value = null
  sqlContent.value = ''
  extractedStatements.value = []
  fileInput.value.value = ''
}

// 切换操作类型选择
const toggleOperation = (operation) => {
  const index = selectedOperations.value.indexOf(operation)
  if (index > -1) {
    selectedOperations.value.splice(index, 1)
  } else {
    selectedOperations.value.push(operation)
  }
}

// SQL语句提取逻辑
const extractSQL = () => {
  if (!sqlContent.value) return

  const statements = []
  const lines = sqlContent.value.split('\n')
  let currentStatement = ''
  let inStatement = false
  let currentLineNumber = 0
  let statementStartLine = 0

  // SQL操作类型正则表达式
  const operationRegex = new RegExp(
    `\\b(${selectedOperations.value.join('|')})\\b`,
    'i'
  )

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim()
    currentLineNumber = i + 1

    // 跳过空行和注释
    if (!line || line.startsWith('--') || line.startsWith('/*') || line.startsWith('*')) {
      continue
    }

    // 检查是否是新语句的开始
    const operationMatch = line.match(operationRegex)
    if (operationMatch && !inStatement) {
      inStatement = true
      currentStatement = line
      statementStartLine = currentLineNumber
    } else if (inStatement) {
      currentStatement += ' ' + line
    }

    // 检查语句是否结束（分号或新语句开始）
    if (inStatement && (line.endsWith(';') || (i < lines.length - 1 && lines[i + 1].trim().match(operationRegex)))) {
      inStatement = false

      // 提取表名和操作类型
      const operation = extractOperation(currentStatement)
      const table = extractTableName(currentStatement, operation)

      // 应用表名过滤
      if (tableFilter.value) {
        const tableRegex = new RegExp(tableFilter.value, 'i')
        if (!tableRegex.test(table)) {
          currentStatement = ''
          continue
        }
      }

      if (operation && table) {
        statements.push({
          sql: currentStatement.trim(),
          operation: operation.toLowerCase(),
          table: table,
          lineNumber: statementStartLine
        })
      }

      currentStatement = ''
    }
  }

  extractedStatements.value = statements
}

// 提取操作类型
const extractOperation = (sql) => {
  const operationMatch = sql.match(/\b(insert|update|delete|create|alter|drop|truncate|replace)\b/i)
  return operationMatch ? operationMatch[1] : null
}

// 提取表名
const extractTableName = (sql, operation) => {
  switch (operation.toLowerCase()) {
    case 'insert':
      const insertMatch = sql.match(/into\s+(\w+)/i)
      return insertMatch ? insertMatch[1] : null
    case 'update':
      const updateMatch = sql.match(/update\s+(\w+)/i)
      return updateMatch ? updateMatch[1] : null
    case 'delete':
      const deleteMatch = sql.match(/from\s+(\w+)/i)
      return deleteMatch ? deleteMatch[1] : null
    case 'create':
    case 'alter':
    case 'drop':
    case 'truncate':
      const tableMatch = sql.match(/\b(table|database)\s+(\w+)/i)
      return tableMatch ? tableMatch[2] : null
    case 'replace':
      const replaceMatch = sql.match(/into\s+(\w+)/i)
      return replaceMatch ? replaceMatch[1] : null
    default:
      return null
  }
}

// 获取操作类型的CSS类
const getOperationClass = (operation) => {
  return `operation-${operation}`
}

// 复制结果到剪贴板
const copyResults = async () => {
  const textToCopy = extractedStatements.value.map(stmt => stmt.sql).join('\n\n')

  try {
    await navigator.clipboard.writeText(textToCopy)
    copyButtonText.value = '已复制!'
    setTimeout(() => {
      copyButtonText.value = '复制结果'
    }, 2000)
  } catch (err) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = textToCopy
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      copyButtonText.value = '已复制!'
      setTimeout(() => {
        copyButtonText.value = '复制结果'
      }, 2000)
    } catch (err2) {
      copyButtonText.value = '复制失败'
      setTimeout(() => {
        copyButtonText.value = '复制结果'
      }, 2000)
    }
    document.body.removeChild(textArea)
  }
}

// 清空所有
const clearAll = () => {
  clearFile()
  selectedOperations.value = ['insert', 'update', 'delete', 'create', 'alter', 'drop']
  tableFilter.value = ''
}

// 统计信息计算属性
const operationStats = computed(() => {
  const stats = {}
  extractedStatements.value.forEach(stmt => {
    stats[stmt.operation] = (stats[stmt.operation] || 0) + 1
  })
  return stats
})

// 监听SQL内容变化，自动提取
watch(sqlContent, (newContent) => {
  if (newContent) {
    extractSQL()
  }
})
</script>

<style scoped>
.btn {
  padding: 8px 15px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 20px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(to right, #1a2a6c, #b21f1f);
  color: white;
}
.retrunBUtton {
  position: absolute;
  top: 100px;
  right: 100px;
}

.sql-extractor {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  position: relative;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.tool-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px;
  text-align: center;
  border-radius: 12px 12px 0 0;
}

.tool-header h1 {
  margin: 0 0 10px 0;
  font-size: 2.2em;
}

.subtitle {
  margin: 0;
  opacity: 0.9;
  font-size: 1.1em;
}

.tool-content {
  padding: 30px;
}

.upload-section {
  margin-bottom: 30px;
}

.upload-area {
  border: 2px dashed #667eea;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background: #f8f9ff;
}

.upload-area:hover {
  border-color: #764ba2;
  background: #f0f2ff;
}

.upload-icon {
  font-size: 3em;
  margin-bottom: 15px;
}

.file-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding: 15px;
  background: #e8f4ff;
  border-radius: 6px;
}

.filter-section {
  background: #f8f9fa;
  padding: 25px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.filter-group {
  margin-bottom: 20px;
}

.filter-group label {
  display: block;
  margin-bottom: 10px;
  font-weight: 600;
  color: #333;
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.operation-buttons button {
  padding: 8px 16px;
  border: 2px solid #ddd;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.operation-buttons button.active {
  background: #667eea;
  color: white;
  border-color: #667eea;
}

.table-input {
  width: 100%;
  max-width: 400px;
  padding: 10px;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 18px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.extract-btn,
.clear-all-btn,
.clear-btn,
.copy-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.extract-btn {
  background: #4caf50;
  color: white;
}

.extract-btn:hover:not(:disabled) {
  background: #45a049;
  transform: translateY(-2px);
}

.clear-all-btn {
  background: #ff9800;
  color: white;
}

.clear-btn {
  background: #f44336;
  color: white;
  padding: 6px 12px;
  font-size: 16px;
}

.copy-btn {
  background: #2196f3;
  color: white;
}

button:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none !important;
}

.result-section {
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
}

.result-content {
  max-height: 500px;
  overflow-y: auto;
}

.empty-state {
  padding: 60px 20px;
  text-align: center;
  color: #666;
}

.empty-icon {
  font-size: 4em;
  margin-bottom: 20px;
}

.statements-list {
  padding: 20px;
}

.statement-item {
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  margin-bottom: 15px;
  overflow: hidden;
}

.statement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
}

.operation-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 600;
  color: white;
}

.table-name {
  font-weight: 600;
  color: #333;
}

.statement-index {
  color: #666;
  font-size: 16px;
}

.statement-sql {
  padding: 15px;
  margin: 0;
  background: #fafafa;
  font-family: 'Courier New', monospace;
  font-size: 18px;
  line-height: 1.4;
  overflow-x: auto;
  white-space: pre-wrap;
}

.statement-meta {
  display: flex;
  justify-content: space-between;
  padding: 8px 15px;
  background: #f0f0f0;
  font-size: 16px;
  color: #666;
}

.stats-section {
  margin-top: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.stat-item {
  background: white;
  padding: 15px;
  border-radius: 6px;
  text-align: center;
  border-left: 4px solid #667eea;
}

.stat-label {
  display: block;
  font-size: 16px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  display: block;
  font-size: 1.5em;
  font-weight: 600;
  color: #333;
}

/* 操作类型颜色 */
.operation-insert .operation-tag {
  background: #4caf50;
}
.operation-update .operation-tag {
  background: #ff9800;
}
.operation-delete .operation-tag {
  background: #f44336;
}
.operation-create .operation-tag {
  background: #2196f3;
}
.operation-alter .operation-tag {
  background: #9c27b0;
}
.operation-drop .operation-tag {
  background: #607d8b;
}
.operation-truncate .operation-tag {
  background: #795548;
}
.operation-replace .operation-tag {
  background: #009688;
}

@media (max-width: 768px) {
  .tool-content {
    padding: 20px;
  }

  .operation-buttons {
    justify-content: center;
  }

  .action-buttons {
    flex-direction: column;
  }

  .result-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}
</style>